package com.atguigu.yygh.cmn.service.impl;

import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-01-10
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    //根据数据的id查询子数据
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean hasChildren = this.hasChildrenById(dictId);
            dict.setHasChildren(hasChildren);
        }
        return dictList;
    }
    //根据参数获取字典数据名称
    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //判断parentDictCode是否为空,如为空,用一个参数查询
        if(StringUtils.isEmpty(parentDictCode)){
            Dict dict = baseMapper.selectOne(
                    new QueryWrapper<Dict>().eq("value", value)
            );
            if(dict!=null){
                return dict.getName();
            }
        }else{
            //根据两个参数查询
            //根据dictcode 查询分类一级信息
            Dict parenDict =  this.getDictByDictCode(parentDictCode);
            //根据parent id和value查询数据
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parenDict.getId())
                    .eq("value", value));
            if(dict!=null){
                return dict.getName();
            }
        }
        return "";
    }

    //根据dictCode获取下级节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict parentDict = baseMapper.selectOne(
                new QueryWrapper<Dict>().eq("dict_code", dictCode));
        List<Dict> dictList = this.findChildData(parentDict.getId());
        return dictList;
    }


    //根据dict_code 查询分类一级信息
    private Dict getDictByDictCode(String parentDictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",parentDictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict;


    }

    //判断有没有子数据
    private boolean hasChildrenById(Long dictId) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",dictId);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }

}
